#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/11/15 17:36
# @Author  : lizhen
# @Site    : 
# @File    : cAccessToken.py
# @Software: PyCharm
import ConfigParser
import datetime
import json
import os
import urllib
import redis

appid_appsecret_cfg = os.environ['user_pswd']
cp = ConfigParser.ConfigParser()
cp.read(appid_appsecret_cfg)
appid = cp.get('WeChat', 'WeChat_APPID')
appsecret = cp.get('WeChat', 'WeChat_APPSecret')
sr = redis.StrictRedis(host="192.168.1.104")


class AccessTokenDemo(object):
    _access_token = {
        'token': '',
        'expires_in': 3600,
        'updatetime': datetime.datetime.now()
    }

    @classmethod
    def get_access_token_temp(cls):
        if not cls._access_token['token'] or (datetime.datetime.now() - cls._access_token['updatetime']).seconds > \
                cls._access_token['expires_in']:
            return cls.__update_access_token_temp()
        else:
            return cls._access_token['token']

    @classmethod
    def __update_access_token_temp(cls):
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}".format(
            appid, appsecret)
        resp = urllib.urlopen(url).read()
        resp_data = json.loads(resp)
        cls._access_token['token'] = resp_data.get('access_token')
        cls._access_token['updatetime'] = datetime.datetime.now()
        return cls._access_token['token']

    @classmethod
    def get_access_token(cls):
        _token = sr.hget(name='wx_accesstoken', key='token')
        _expires_in = sr.hget(name='wx_accesstoken', key='expires_in')
        _updatetime = sr.hget(name='wx_accesstoken', key='updatetime')
        if not _token or (datetime.datetime.now() - datetime.datetime.strptime(_updatetime, '%Y-%m-%d %H:%M:%S.%f'
                                                                               )).seconds > int(_expires_in):
            return cls.__update_access_token()
        else:
            return _token

    @classmethod
    def __update_access_token(cls):
        url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}".format(
            appid, appsecret)
        resp = urllib.urlopen(url).read()
        resp_data = json.loads(resp)
        _token_dict = {'token': resp_data.get('access_token'), 'updatetime': str(datetime.datetime.now()),
                       'expires_in': 3600}
        sr.hmset(name='wx_accesstoken', mapping=_token_dict)
        return sr.hget(name='wx_accesstoken', key='token')

    def _test_accesstoken(self):
        """
        atd = AccessTokenDemo()
        atd._test_accesstoken()
        """
        # print AccessTokenDemo.get_access_token_temp()
        print AccessTokenDemo.get_access_token()


if __name__ == '__main__':
    atd = AccessTokenDemo()
    atd._test_accesstoken()
